const websocket = require('ws');
const ws = new websocket.Server({ port: 8081 })

let clients = {}
let clientname = 0;
ws.on('connection', (client) => {
  client.name = ++clientname;
  clients[clientname] = client;

  client.on('message', (msg) => {
    broadcast(client, msg)
  })

  client.on('close', () => {
    delete clients[client.name];
    console.log(client.name + '下线了')
  })

})

function broadcast(client, msg) {
  for (let key in clients) {
    clients[key].send(client.name + '说：' + msg)
  }
}